//
// Created by hunan on 2025/10/2.
//

#include "bw_statistic.h"

#include "../log_module/log_public_module.h"
#include "../timer/timer_task.h"

#include <atomic>

BWStatistic::BWStatistic(Loop * loop)
{
    m_loop            = loop;
    m_interval_second = 0;
    m_statistic_num.store(0);
    m_statistic_tm.store(0);
}

void BWStatistic::StartStatistic(uint32_t interval_second)
{
    if (!m_timer_task && interval_second > 0)
    {
        struct timeval tv = {};
        gettimeofday(&tv, nullptr);
        m_statistic_tm    = tv.tv_sec;
        m_interval_second = interval_second;
        m_timer_task      = std::make_shared<TimerTask>(m_loop);
        m_timer_task->ExpireFromNow(m_interval_second * 1000, [this]() { Statistic(); });
    }
}

void BWStatistic::StopStatistic()
{
    if (m_timer_task)
    {
        m_timer_task->Cancel();
        m_interval_second = 0;
        m_statistic_num   = 0;
        m_statistic_tm    = 0;
    }
}

void BWStatistic::operator+=(const int number)
{
    if (number > 0)
    {
        m_statistic_num.fetch_add(number);
    }
}

void BWStatistic::Statistic()
{
    LOG_STATISTIC_MODULE("BWStatistic(%p) Statistic time:%ld bw:%.2lfMB/s", this, m_statistic_tm.load(),
                         m_statistic_num / 1024.0);
    struct timeval tv = {};
    gettimeofday(&tv, nullptr);
    m_statistic_tm  = tv.tv_sec;
    m_statistic_num = 0;
    m_timer_task->ExpireFromNow(m_interval_second * 1000, [this]() { Statistic(); });
}
